package com.ruoyi.ai.api;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.ai.api.vo.WxDictDataVo;
import com.ruoyi.ai.service.url.DomainService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微信小程序-通用功能
 */
@Validated
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/wx/ma/common")
public class WxMaCommonController {
    private final ISysDictTypeService dictTypeService;
    private final DomainService domainService;

    /**
     * 根据字典类型查询字典数据信息
     *
     * @param dictType 字典类型
     */
    @GetMapping(value = "/type/{dictType}")
    public R<List<WxDictDataVo>> dictType(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (ObjectUtil.isNull(data)) {
            data = new ArrayList<>();
        }
        List<WxDictDataVo> resultList = data.stream().map(d -> {
            WxDictDataVo wxDictDataVo = new WxDictDataVo();
            BeanUtils.copyProperties(d, wxDictDataVo);
            return wxDictDataVo;
        }).collect(Collectors.toList());
        return R.ok(resultList);
    }

    /**
     * 通用上传请求（上传到本地）
     */
    @PostMapping("/uploadLocal")
    public R<Map<String, String>> uploadFile(MultipartFile file) throws Exception {
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = domainService.getUrl() + fileName;
        Map<String, String> data = new HashMap<>();
        data.put("url", url);
        data.put("fileName", fileName);
        data.put("newFileName", FileUtils.getName(fileName));
        data.put("originalFilename", file.getOriginalFilename());
        return R.ok(data);
    }
}
